﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PicklistXMLGenerator
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            
            string[] lines = txtSource.Text.Split(Environment.NewLine.ToCharArray());

            try
            {
                txtResult.Text = "";
                txtResult.AppendText("<options>" + Environment.NewLine);

                List<string> workList = lines.ToList();

                // Sort and filter out blank/bad entries
                if (chkSortByDescription.Checked == true)
                {
                    lines = (from w in workList
                             where w.Split(new char[] { ',' }, 2).Count() == 2
                             orderby w.Split(new char[] { ',' }, 2)[1].Replace("\"", "")
                             select w).ToArray();
                }
                else
                {
                    lines = (from w in workList
                             where w.Split(new char[] { ',' }, 2).Count() == 2
                             select w).ToArray();
                }
                foreach (string line in lines)
                {
                    string[] substrings = line.Split(new char[] { ',' }, 2);

                    int id = int.Parse(substrings[0]);
                    string value = substrings[1].Replace("\"", "");

                    txtResult.AppendText("  <option value=\"" + id.ToString() + "\">" + Environment.NewLine);
                    txtResult.AppendText("    <labels>" + Environment.NewLine);
                    txtResult.AppendText("      <label description=\"" + value + "\" languagecode=\"" + txtLanguageCode.Text + "\" />" + Environment.NewLine);
                    txtResult.AppendText("    </labels>" + Environment.NewLine);
                    txtResult.AppendText("  </option>" + Environment.NewLine);
                }
                txtResult.AppendText("</options>");
            }
            catch (Exception ex)
            {
                txtResult.Text = "ERROR";
                MessageBox.Show(ex.Message);
                
            }
        }

    }
}
